import { http } from "@/utils/http";
import type {
  ListOption,
  Service,
  ServiceAccountList,
  ServiceList
} from "./types";
import type { BaseResponse, PromiseRes } from "@/api/response";
import {
  k8sPathMergeReqs,
  type MakePathReq,
  type MergePathReq
} from "./apiHelper";
export type ServiceQuery = ListOption & {
  namespace?: string;
  name?: string;
  clusterName?: string;
};

export class K8sService {
  baseReq: MakePathReq = {
    src: "services",
    app: ""
  };

  getService = (query: MergePathReq): BaseResponse<ServiceList> => {
    const api = k8sPathMergeReqs(query, this.baseReq);

    return http.get(api);
  };

  getServiceDetail = (query: MergePathReq): BaseResponse<Service> => {
    const api = k8sPathMergeReqs(query, this.baseReq);

    return http.get(api);
  };

  updateService = (query?: ServiceQuery): PromiseRes => {
    return http.put(
      `/api/v1/kubeHud/k8s/service/${query.namespace}/${query.name}`,
      { params: query }
    );
  };

  deleteService = (query?: ServiceQuery): PromiseRes => {
    return http.delete("/api/v1/kubeHud/k8s/service/del", { params: query });
  };

  createService = (data?: ServiceQuery): PromiseRes => {
    return http.post("/api/v1/kubeHud/k8s/service/create", { data });
  };
}

export class K8sServiceAccount {
  serviceAccountUrl = cluster_name => {
    return `/api/v1/proxy/${cluster_name}/k8s/api/v1/serviceaccounts`;
  };
  namespaceServiceAccountUrl = (cluster_name, namespace) => {
    return `/api/v1/proxy/${cluster_name}/k8s/api/v1/namespaces/${namespace}/serviceaccounts`;
  };

  listServiceAccounts(
    cluster_name: string,
    keywords?: string,
    pageNum?: number,
    pageSize?: number
  ): BaseResponse<ServiceAccountList> {
    let url = this.serviceAccountUrl(cluster_name);
    const params = {};
    if (keywords) {
      params["search"] = true;
      if (keywords) {
        params["keywords"] = keywords;
      }
      if (pageNum && pageSize) {
        params["pageNum"] = pageNum;
        params["pageSize"] = pageSize;
      }
    }
    return http.get(url, params);
  }

  listServiceAccountsWithNs(
    cluster_name,
    namespace
  ): BaseResponse<ServiceAccountList> {
    return http.get(
      `${this.namespaceServiceAccountUrl(cluster_name, namespace)}`
    );
  }

  deleteServiceAccount(cluster_name, namespace, name) {
    return http.delete(
      `${this.namespaceServiceAccountUrl(cluster_name, namespace)}/${name}`
    );
  }

  getServiceAccount(cluster_name, namespace, name) {
    return http.get(
      `${this.namespaceServiceAccountUrl(cluster_name, namespace)}/${name}`
    );
  }

  createServiceAccount(cluster_name, namespace, data) {
    return http.post(
      `${this.namespaceServiceAccountUrl(cluster_name, namespace)}`,
      data
    );
  }

  updateServiceAccount(cluster_name, namespace, name, data) {
    return http.put(
      `${this.namespaceServiceAccountUrl(cluster_name, namespace)}/${name}`,
      data
    );
  }
}
